<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <!-- 页面标题 -->
      <div class="text-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-2">学习概览</h1>
        <p class="text-lg text-gray-600">欢迎回来，{{ authStore.user?.profile?.firstName }} {{ authStore.user?.profile?.lastName }}！</p>
      </div>

      <!-- 总体学习统计 -->
      <div class="bg-white rounded-lg shadow-md p-6 mb-8">
        <h2 class="text-xl font-semibold text-gray-800 mb-4">学习统计</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div class="text-center">
            <div class="text-3xl font-bold text-blue-600">{{ totalProgress }}%</div>
            <div class="text-sm text-gray-600">总体进度</div>
          </div>
          <div class="text-center">
            <div class="text-3xl font-bold text-green-600">{{ completedChapters }}</div>
            <div class="text-sm text-gray-600">已完成章节</div>
          </div>
          <div class="text-center">
            <div class="text-3xl font-bold text-orange-600">{{ totalStudyTime }}</div>
            <div class="text-sm text-gray-600">学习时长(分钟)</div>
          </div>
        </div>
      </div>

      <!-- 章节学习进度 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div 
          v-for="chapter in chapters" 
          :key="chapter.id"
          class="bg-white rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow cursor-pointer"
          @click="goToChapter(chapter.id)"
        >
          <!-- 章节标题 -->
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-gray-800">{{ chapter.title }}</h3>
            <div class="flex items-center">
              <span class="text-sm text-gray-500 mr-2">{{ chapter.progress }}%</span>
              <div class="w-8 h-8 rounded-full flex items-center justify-center"
                   :class="getChapterStatusClass(chapter.progress)">
                <svg v-if="chapter.progress === 100" class="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
                  <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"></path>
                </svg>
                <span v-else class="text-xs font-medium text-white">{{ Math.round(chapter.progress / 20) }}</span>
              </div>
            </div>
          </div>

          <!-- 进度条 -->
          <div class="w-full bg-gray-200 rounded-full h-2 mb-4">
            <div 
              class="h-2 rounded-full transition-all duration-300"
              :class="getProgressBarClass(chapter.progress)"
              :style="{ width: chapter.progress + '%' }"
            ></div>
          </div>

          <!-- 学习详情 -->
          <div class="space-y-2">
            <div class="flex justify-between text-sm">
              <span class="text-gray-600">视频观看:</span>
              <span class="font-medium">{{ chapter.videosWatched }}/{{ chapter.totalVideos }}</span>
            </div>
            <div class="flex justify-between text-sm">
              <span class="text-gray-600">资料点击:</span>
              <span class="font-medium">{{ chapter.materialsClicked }}</span>
            </div>
            <div class="flex justify-between text-sm">
              <span class="text-gray-600">最后学习:</span>
              <span class="font-medium">{{ formatLastStudyTime(chapter.lastStudyTime) }}</span>
            </div>
          </div>

          <!-- 最近学习活动 -->
          <div v-if="chapter.recentActivities && chapter.recentActivities.length > 0" class="mt-4">
            <h4 class="text-sm font-medium text-gray-700 mb-2">最近活动</h4>
            <div class="space-y-1">
              <div 
                v-for="activity in chapter.recentActivities.slice(0, 3)" 
                :key="activity.id"
                class="text-xs text-gray-600 bg-gray-50 rounded px-2 py-1"
              >
                {{ formatActivity(activity) }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 学习建议 -->
      <div class="mt-8 bg-blue-50 rounded-lg p-6">
        <h2 class="text-xl font-semibold text-blue-800 mb-4">学习建议</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div v-for="suggestion in suggestions" :key="suggestion.id" class="flex items-start space-x-3">
            <div class="flex-shrink-0 w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center mt-0.5">
              <svg class="w-4 h-4 text-blue-600" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"></path>
              </svg>
            </div>
            <div>
              <h3 class="text-sm font-medium text-blue-800">{{ suggestion.title }}</h3>
              <p class="text-sm text-blue-600">{{ suggestion.description }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { request } from '@/config/api'
import type { StudentProgress } from '@/services/progressService'

const router = useRouter()
const authStore = useAuthStore()

// 定义章节类型
interface Chapter {
  id: number
  title: string
  progress: number
  videosWatched: number
  totalVideos: number
  materialsClicked: number
  lastStudyTime: string | null
  recentActivities: StudentProgress[]
}

// 响应式数据
const chapters = ref<Chapter[]>([
  {
    id: 1,
    title: '第1章 绪论',
    progress: 0,
    videosWatched: 0,
    totalVideos: 2,
    materialsClicked: 0,
    lastStudyTime: null,
    recentActivities: [] as StudentProgress[]
  },
  {
    id: 2,
    title: '第2章 开发环境',
    progress: 0,
    videosWatched: 0,
    totalVideos: 2,
    materialsClicked: 0,
    lastStudyTime: null,
    recentActivities: [] as StudentProgress[]
  },
  {
    id: 3,
    title: '第3章 Vue.js基础',
    progress: 0,
    videosWatched: 0,
    totalVideos: 8,
    materialsClicked: 0,
    lastStudyTime: null,
    recentActivities: [] as StudentProgress[]
  },
  {
    id: 4,
    title: '第4章 Vue.js进阶',
    progress: 0,
    videosWatched: 0,
    totalVideos: 4,
    materialsClicked: 0,
    lastStudyTime: null,
    recentActivities: [] as StudentProgress[]
  },
  {
    id: 5,
    title: '第5章 Vue.js实战',
    progress: 0,
    videosWatched: 0,
    totalVideos: 4,
    materialsClicked: 0,
    lastStudyTime: null,
    recentActivities: [] as StudentProgress[]
  }
])

const suggestions = ref([
  {
    id: 1,
    title: '继续学习',
    description: '建议从第1章开始系统学习'
  },
  {
    id: 2,
    title: '复习巩固',
    description: '定期回顾已学内容，加深理解'
  },
  {
    id: 3,
    title: '实践练习',
    description: '多做练习，将理论转化为实践'
  },
  {
    id: 4,
    title: '交流讨论',
    description: '与同学交流学习心得和疑问'
  }
])

// 计算属性
const totalProgress = computed(() => {
  const total = chapters.value.reduce((sum, chapter) => sum + chapter.progress, 0)
  return Math.round(total / chapters.value.length)
})

const completedChapters = computed(() => {
  return chapters.value.filter(chapter => chapter.progress === 100).length
})

const totalStudyTime = computed(() => {
  // 这里可以根据实际的学习记录计算总学习时长
  return chapters.value.reduce((sum, chapter) => {
    return sum + (chapter.videosWatched * 15) + (chapter.materialsClicked * 5) // 假设每个视频15分钟，每次资料点击5分钟
  }, 0)
})

// 方法
const getChapterStatusClass = (progress: number) => {
  if (progress === 100) {
    return 'bg-green-500'
  } else if (progress >= 50) {
    return 'bg-blue-500'
  } else if (progress > 0) {
    return 'bg-orange-500'
  } else {
    return 'bg-gray-300'
  }
}

const getProgressBarClass = (progress: number) => {
  if (progress === 100) {
    return 'bg-green-500'
  } else if (progress >= 50) {
    return 'bg-blue-500'
  } else if (progress > 0) {
    return 'bg-orange-500'
  } else {
    return 'bg-gray-300'
  }
}

const formatLastStudyTime = (time: string | null) => {
  if (!time) return '未开始'
  const date = new Date(time)
  const now = new Date()
  const diffTime = Math.abs(now.getTime() - date.getTime())
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 1) {
    return '今天'
  } else if (diffDays === 2) {
    return '昨天'
  } else if (diffDays <= 7) {
    return `${diffDays}天前`
  } else {
    return date.toLocaleDateString()
  }
}

const formatActivity = (activity: any) => {
  const actionMap: { [key: string]: string } = {
    'video_watch': '观看视频',
    'material_click': '查看资料',
    'exercise_complete': '完成练习'
  }
  return `${actionMap[activity.actionType] || activity.actionType}: ${activity.details || ''}`
}

const goToChapter = (chapterId: number) => {
  const routeMap: { [key: number]: string } = {
    1: '/chapter1',
    2: '/chapter2',
    3: '/chapter3-examples',
    4: '/chapter4-examples',
    5: '/examples'
  }
  router.push(routeMap[chapterId] || '/chapter1')
}

// 加载学习进度数据
const loadStudentProgress = async () => {
  try {
    if (!authStore.user?.id) return
    
    const progressData = await request<StudentProgress[]>('/student-progress/user/current')
    
    // 更新章节进度数据
    chapters.value.forEach(chapter => {
      const chapterProgress = progressData.filter((p: any) => p.chapterId === chapter.id.toString())
      
      if (chapterProgress.length > 0) {
        // 计算章节进度
        const videoWatches = chapterProgress.filter((p: any) => p.actionType === 'video_watch')
        const materialClicks = chapterProgress.filter((p: any) => p.actionType === 'material_click')
        
        chapter.videosWatched = Math.min(videoWatches.length, chapter.totalVideos)
        chapter.materialsClicked = materialClicks.length
        
        // 计算进度百分比（视频观看占70%，资料点击占30%）
        const videoProgress = (chapter.videosWatched / chapter.totalVideos) * 70
        const materialProgress = Math.min(chapter.materialsClicked / 5, 1) * 30 // 假设点击5次资料算完成
        chapter.progress = Math.round(videoProgress + materialProgress)
        
        // 获取最后学习时间
        const sortedProgress = chapterProgress.sort((a: any, b: any) => 
          new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
        )
        chapter.lastStudyTime = sortedProgress[0]?.timestamp
        
        // 获取最近活动（最近5条）
        chapter.recentActivities = sortedProgress.slice(0, 5)
      }
    })
    
    // 更新学习建议
    updateSuggestions()
  } catch (error) {
    console.error('加载学习进度失败:', error)
  }
}

// 更新学习建议
const updateSuggestions = () => {
  const newSuggestions = []
  
  // 找到下一个应该学习的章节
  const nextChapter = chapters.value.find(chapter => chapter.progress < 100)
  if (nextChapter) {
    newSuggestions.push({
      id: 1,
      title: '继续学习',
      description: `建议继续学习${nextChapter.title}`
    })
  }
  
  // 检查是否有很久没学习的章节
  const staleChapters = chapters.value.filter(chapter => {
    if (!chapter.lastStudyTime) return false
    const daysSinceLastStudy = Math.abs(new Date().getTime() - new Date(chapter.lastStudyTime).getTime()) / (1000 * 60 * 60 * 24)
    return daysSinceLastStudy > 7 && chapter.progress > 0 && chapter.progress < 100
  })
  
  if (staleChapters.length > 0) {
    newSuggestions.push({
      id: 2,
      title: '复习巩固',
      description: `建议复习${staleChapters[0].title}，已有一周未学习`
    })
  }
  
  // 添加默认建议
  newSuggestions.push(
    {
      id: 3,
      title: '实践练习',
      description: '多做练习，将理论转化为实践'
    },
    {
      id: 4,
      title: '交流讨论',
      description: '与同学交流学习心得和疑问'
    }
  )
  
  suggestions.value = newSuggestions.slice(0, 4)
}

// 组件挂载时加载数据
onMounted(() => {
  loadStudentProgress()
})
</script>

<style scoped>
/* 自定义样式 */
.transition-all {
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 300ms;
}
</style>